package com.example.zp.jcenterupload.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

public class SimpleTabHost extends LinearLayout {

	private int INVALID_POSITION = -1;
	private OnClickListenerTab mOnTabClickListener;
	private View mLastTabView;
	private OnTabSelectedListener mOnTabSelectedListener;
	private static int DEFAULT_SELECT = 0;
	private int mPosition = DEFAULT_SELECT;

	public SimpleTabHost(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnHierarchyChangeListener(new OnHierarchyChangeListener() {

			@Override
			public void onChildViewRemoved(View parent, View child) {

			}

			@Override
			public void onChildViewAdded(View parent, View child) {
				if (mOnTabClickListener == null) {
					mOnTabClickListener = new OnClickListenerTab();
				}
				int position = getPositionForView(child);
				child.setOnClickListener(mOnTabClickListener);
				if (position == DEFAULT_SELECT) {
					setTabSelect(position);
				}
			}
		});
	}

	public SimpleTabHost(Context context) {
		super(context);
	}

	class OnClickListenerTab implements OnClickListener {
		@Override
		public void onClick(View v) {
			mPosition = getPositionForView(v);
			setTabSelect(mPosition);
		}
	}

	public void clearFoucs() {
		// TODO
		if (mLastTabView != null) {
			mLastTabView.setSelected(false);
			mLastTabView = null;
		}
	}
	public void setTabSelectN(int position) {
		if (mLastTabView != null) {
			mLastTabView.setSelected(false);
		}
		View v = null;
		try {
			v = getChildAt(position);
			if (v != null) {
				v.setSelected(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mLastTabView = v;
		}
	}

	public void setTabSelect(int position) {
		if (mLastTabView != null) {
			mLastTabView.setSelected(false);
		}
		View v = null;
		try {
			v = getChildAt(position);
			if (v != null) {
				v.setSelected(true);
				if (mOnTabSelectedListener != null && mLastTabView != v) {
					mOnTabSelectedListener.onTabSelect(v, position);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mLastTabView = v;
		}
	}

	public int getPositionForView(View view) {
		View listItem = view;
		try {
			View v;
			while (!(v = (View) listItem.getParent()).equals(this)) {
				listItem = v;
			}
		} catch (ClassCastException e) {
			return INVALID_POSITION;
		}
		final int childCount = getChildCount();
		for (int i = 0; i < childCount; i++) {
			if (getChildAt(i).equals(listItem)) {
				return i;
			}
		}

		return INVALID_POSITION;
	}

	/**
	 * 
	 *
	 */
	public interface OnTabSelectedListener {
		void onTabSelect(View v, int position);
	}

	public void setOnTabSelectedListener(OnTabSelectedListener listener) {
		this.mOnTabSelectedListener = listener;
	}

}
